
# use with rep_meas_formatted.csv, BDIdummyeg.txt and mixedfunc.txt 
# create the .csv file and BDIdummyeg.txt file with tab delimiters using EXCEL file inputs

#first have to reshape the data; R uses long format data in its ANOVA and GLM procedures with each response, rather than each subject,
# (broad format) on each row as in the rep_meas_formatted.csv data file

# we will add in libraries to our R session from our library folder as we go along that contain functions we will be using or install these
# from the internet into our library if they are not already there
install.packages(c('reshape','car'))
library(car)
#library(foreign)
library(reshape)

zz <- file.path("U:","My Documents")
#normalizePath(zz)

# mixed models
##Using ggplot and the effects packages to plot 95% CI boxplots (as used by Adam W for Sarah Simblett data random intercept model using lmer) in lmer ggplot
95% CIs AW 31.08.2014 and CIs using lmer in R using ggplot.doc both in this folder

#The below works fine with the BDIdata and BDIdummyeg text data using R 2.14

#library (foreign) # make available data import/export commands
library (graphics) # makes graphics available
library (stats) # makes some important stats available, eg nlm
library (nlme) # makes nlme and lme available
library (lme4)

#BDIData <- read.spss("U:\\My Documents\\BDIdummyeg.sav")
#The data file in EXCEL uses variable labels for the factors rather than numerics; the effect function only treats time and grp as factors 
# if it sees words instead of numbers for variable values; may therefore need to find and replace for any numerics in EXCEL data files
# prior to saving as tabl delimited text files for read.table to read in

# Adapted with thanks from original code by Adam Wagner

BDIData <- read.table("U:\\My Documents\\BDIdummyeg.txt",header=T)
BDIData <- data.frame(BDIData)
BDIData$BDI[BDIData$BDI==999] <- NA
BDIData <- na.omit(BDIData) 
attach(BDIData)

bdiModelA   <- lmer(BDI~grp*time+Gender+BDIcategory + (1|id),
                   data=BDIData)

bdiModelB1 <- update(bdiModelA, .~. - grp:time)


# 95% CIs not produced as intervals doesn't work with lmer but we will get these using lme
intervals(bdiModelA)

bdiModelB    <- lme (BDI~grp*time+Gender+BDIcategory , random=~1|id,
                   data=BDIData)

intervals(bdiModelB)
summary(bdiModelB)
# using lmer you don't get the p-values otherwise identical to output from lme
summary(bdiModelA)

anova(bdiModelB1)
#anova(bdiModelA,bdiModelB1)

#library(lmerTest)
# gives p-values including p-value for grp:time which has an identical F value to that comparing 
# bdiModelA and bdiModelB  as above; p-values outputted only with lme and not lmer
anova(bdiModelB)
# lmer identical output to using lme just now but with no p-values
anova(bdiModelA)

# residual plots

plot(ranef(bdiModelB))
# qqmath only works with lmer objects using lattice library giving 95% Cis for standardised intercepts
library(lattice)
qqmath(ranef(bdiModelB1))
# can use lme objects for residuals plots
res_lme=residuals(bdiModelB)
plot(res_lme)
qqnorm(res_lme)
qqline(res_lme)
# residuals against fitted values plot
fval <- plot(bdiModelB)
fval

#install.packages("effects")

library(effects)
ef <- effect("grp:time", bdiModelA)
summary(ef)
xd <- as.data.frame(ef)

# the difference of form: 
# (time k - baseline) in treatment - ( time k - baseline) in controls = (31.87-28.97) - #(27.65-30.09) = 2.90 + 2.44  # =  5.34 is 
# represented by the grpTreatment:timePost regression coefficient in bdiModelA in lmer and bdiModelB in lme

# Plotting of effect sizes in mixed model syntax by Adam Wagner

library(plotrix)
XLabel <- "Time point"
YLabel <- "Average BDI-II score"
subLabel <- "N= observations in each group by time combination"
grpTitle <- "BDI-II profiles: Mean and 95% CI"
timeLabels <- c("Baseline", "Post", "Follow-up","1-month","3-months")
nObsYLine <- 2
groupPch <- c(15, 16)
groupCol <- c(1,2)
# X Locations
xCentrePts <- c(1, 2, 3, 4, 5) 
xLims <- c(0.65, 5.45)
xSplt <- 0.25


# Determine plotting points
xPts <- rep(c(-xSplt, xSplt), 5)
xPts <- rep(xCentrePts, each=2)+xPts
with(xd, plotCI(xPts, fit, ui=upper, li=lower,
                             xlim=xLims,
                             ylim=c(0,50), xaxt="n", xlab=XLabel, ylab=YLabel,
                             col=groupCol[as.numeric(grp)], pch=groupPch[as.numeric(grp)]),sub=subLabel,main=grpTitle)

# can add extras

#abline(v=c(mean(xCentrePts[1:5]), mean(xCentrePts[2:4])), lty=2)
abline(v=c(1.5,0), lty=2)
abline(v=c(2.5,0), lty=2)
abline(v=c(3.5,0), lty=2)
abline(v=c(4.5,0), lty=2)
# Label time points
axis(1, xCentrePts, timeLabels)
legend(x="top", c("Control", "Treatment"), pch=groupPch,
       col=groupCol)
# Include observations at each combination of group and time
#text(x=xPts, y=nObsYLine, 
#    labels=paste("N=", bdiObsN$Freq, sep=""))
#dev.off()

# simpler alternative
library(ggplot2)
ggplot(xd, aes(time, fit, color=grp)) + geom_point() + geom_errorbar(aes(ymin=fit-se, ymax=fit+se), width=0.4) + theme_bw(base_size=12)   


# reading in as a function

library (graphics) # makes graphics available
library (stats) # makes some important stats available, eg nlm
library (nlme) # makes nlme and lme available
library (lme4)
BDIData <- read.table("U:\\My Documents\\BDIdummyeg.txt",header=T)
BDIData <- data.frame(BDIData)
BDIData$BDI[BDIData$BDI==999] <- NA
BDIData <- na.omit(BDIData) 
attach(BDIData)
# To create the sourcefile save the text in a text file (.txt) called mixedfunc.R (a R file called mixedfunc should then show up with a notepad icon) # Then read in this file adding a .R into the function call as below
# each function can only return one output so put return() around what you'd like outputted and do in separate functions
source("U:\\My Documents\\mixedfunc.R")
# returns group x time interaction test
mixfun1(yy<-BDI)
# returns 95% CIs for the full mixed model with grp x time present
mixfun2(yy<-BDI)